<?php
declare (strict_types = 1);

namespace app\admin\controller;

use think\Exception;
use think\exception\ValidateException;
use think\facade\Log;
use think\facade\View;
use think\response\Json;

class Category extends Base {

    public function index() : string {

        $pid = $this->request->param("pid", 0, "intval");
        $page = $this->request->param("page", 1, "intval");

        $data["where"] = [
            ["pid", "=", $pid],
        ];
        $categoryBusi = new \app\business\Category();
        $result = $categoryBusi->pageList($page, $data);
        $category = $categoryBusi->load($pid);

        // 获取分类列表的子分类数量
        if ($result && isset($result["data"]) && count($result["data"]) > 0) {
            $pidArr = array_column($result["data"], "id");
            $childCategoryCountList = $categoryBusi->getCountListByPids($pidArr);
            $childCountByPid = [];
            if ($childCategoryCountList && count($childCategoryCountList) > 0) {
                $childCountByPid = array_combine(array_column($childCategoryCountList, "pid"),
                    array_column($childCategoryCountList, "count"));
            }
            foreach ($result["data"] as $key=>$item){
                $result["data"][$key]["childCount"] = $childCountByPid && isset($childCountByPid[$item["id"]]) ? $childCountByPid[$item["id"]] : 0;
            }
        }

        return View::fetch("", [
            "result" => $result,
            "category" => $category
        ]);
    }

    public function add() : string {

        $categories = (new \app\business\Category())->list(0, "id, pid, name");

        return View::fetch('', [
            "categories" => json_encode($categories)
        ]);
    }

    public function edit() {

        $currentId = $this->request->param("id", 0, "intval");
        if ($currentId <= 0) {
            return redirect("index");
        }
        $categories = (new \app\business\Category())->list($currentId, "id, pid, name");

        return View::fetch('', [
            "categories" => json_encode($categories)
        ]);
    }

    /**
     *  添加或者修改
     * @return Json
     */
    public function save() : Json {
        $data["id"] = $this->request->param("id", 0, "intval");
        $data["name"] = $this->request->param("name", 0, "trim");
        $data["pid"] = $this->request->param("pid", 0, "intval");
        $data["url_key"] = $this->request->param("url_key", 0, "trim");
        $data["list_order"] = $this->request->param("list_order", 0, "intval");

        try{
            validate(\app\admin\validate\Category::class)->scene("save")->check($data);
        }catch (ValidateException $e){
            return show(config("status.error"), $e->getMessage());
        }

        try{
            $data["operate_user"] = $this->admin["username"];
            $result = (new \app\admin\business\Category())->save($data);
            if ($result == false) {
                return show(config("status.error"), "添加失败");
            }
        }catch (Exception $e){
            return show(config("status.error"), $e->getMessage());
        }

        return show(config("status.success"), "保存成功");
    }

    /**
     * 列表页面的字段更新
     * @return Json
     */
    public function update() : Json {
        $data["id"] = $this->request->param("id", 0, "intval");
        $data["field"] = $this->request->param("field", "", "trim");
        $data["val"] = $this->request->param("val", "", "trim");

        if ($data["id"] <= 0) {
            return show(config("status.error"), "没有获取该数据的唯一标识.");
        }

        try{
            validate(\app\admin\validate\Category::class)->scene("update")->check($data);
        }catch (ValidateException $e){
            return show(config("status.error"), $e->getMessage());
        }

        try{
            $update["operate_user"] = $this->admin["username"];
            $update[$data["field"]] = $data["val"];
            $id = $data["id"];
            unset($data);
            $result = (new \app\admin\business\Category())->updateById($id, $update);
            if ($result == false) {
                return show(config("status.error"), "更新失败");
            }
        }catch (Exception $e){
            return show(config("status.error"), $e->getMessage());
        }

        return show(config("status.success"), "更新成功");
    }

    /**
     *  通过ID删除分类
     * @return Json
     */
    public function delete() : Json {
        $data["id"] = $this->request->param("id", 0, "intval");

        try{
            validate(\app\admin\validate\Category::class)->scene("delete")->check($data);
        }catch (ValidateException $e){
            return show(config("status.error"), $e->getMessage());
        }

        try{
            $result = (new \app\admin\business\Category())->deleteById($data["id"], $this->admin["username"]);
            if ($result == false) {
                return show(config("status.error"), "删除失败");
            }
        }catch (Exception $e){
            return show(config("status.error"), $e->getMessage());
        }

        return show(config("status.success"), "删除成功");
    }

    /**
     *  选择分类弹出层
     * @return string
     */
    public function dialog() :string {

        $categoryies = [];
        try{
            $categoryies = (new \app\business\Category())->getListByPid();
        }catch (Exception $e){
            Log::error($e->getMessage());
        }
        return View::fetch("", [
            "categories" => json_encode($categoryies)
        ]);
    }

    public function getChildList() {
        $pid =  $this->request->param("pid", 0, "intval");
        if ($pid <= 0) {
            return show(config("status.error"), "pid不正确");
        }
        $categoryies = [];
        try{
            $categoryies = (new \app\business\Category())->getListByPid($pid);
        }catch (Exception $e){
            Log::error($e->getMessage());
            return show(config("status.error"), "获取子分类失败");
        }

        return show(config("status.success"), "ok", $categoryies);
    }
}